package com.itheima.app.manager;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.UserLike;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FriendService;
import com.itheima.service.mongo.ShowUserService;
import com.itheima.vo.ShowUserVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class CardsUserManager {

    @DubboReference
    ShowUserService showUserService;
    @DubboReference
    UserInfoService userInfoService;
    @DubboReference
    FriendService friendService;
    @Autowired
    HuanXinTemplate huanXinTemplate;

    public ResponseEntity showCardsUser() {
        //获取登陆者用户id
        Long userId = UserHolder.get().getId();

        //创建新集合 volist
        List<ShowUserVo> voList = new ArrayList<>();

        //调用service查询数据
        List<RecommendUser> recommendUsers = showUserService.ShowUserCards(userId);

        if (CollUtil.isNotEmpty(recommendUsers)){

            for (RecommendUser recommendUser : recommendUsers) {
                //根据用户id查询userinfo
                UserInfo userinfo = userInfoService.findByUserId(recommendUser.getUserId());
                //封装vo对象
                ShowUserVo vo = new ShowUserVo();

                vo.setUserInfo(userinfo);

                voList.add(vo);
            }
        }
        System.out.println(voList);
        return ResponseEntity.ok(voList);
    }

    //不喜欢
    public void unLove(Long likeUserId) {
        //获取当前登录者id
        Long userId = UserHolder.get().getId();

        //远程调用service删除推荐数据
        showUserService.unLove(userId,likeUserId);

    }

    //卡片喜欢
    public void userLove(Long likeUserId) {
        //获取当前登陆者id
        Long userId = UserHolder.get().getId();

        //封装userLike对象
        UserLike vo = new UserLike();
        vo.setCreated(System.currentTimeMillis());
        vo.setUserId(userId);
        vo.setLikeUserId(likeUserId);

        showUserService.love(vo);

        //远程调用service删除推荐数据 为了保证下次不再推荐该用户
        showUserService.unLove(userId,likeUserId);

        //查看双方是否互相喜欢 如若是则添加好友 添加环信好友
        boolean eachOther = showUserService.likeEachOther(userId, likeUserId);

        if (eachOther){
            //调用friendService 添加数据库好友
            friendService.saveContact(userId,likeUserId);

            //调用环信模板添加环信好友
            huanXinTemplate.addContacts("HX"+userId,"HX"+likeUserId);
        }
    }
}
